package org.jivesoftware.launcher;

import com.install4j.api.actions.InstallAction;
import com.install4j.api.context.Context;
import com.install4j.api.context.InstallerContext;
import com.install4j.api.context.UserCanceledException;
import com.install4j.api.windows.RegistryRoot;
import com.install4j.api.windows.WinRegistry;

import java.io.File;

public class Installer implements InstallAction
{
	public int getPercentOfTotalInstallation()
	{
		return 0;
	}
	
	public void init(Context context)
	{
	}
	
	public boolean install(InstallerContext installerContext) throws UserCanceledException
	{
		final String osName = System.getProperty("os.name").toLowerCase();
		boolean isWindows = osName.startsWith("windows");
		
		if (!isWindows)
		{
			return true;
		}
		
		final File sparkDirectory;
		String sparkPath = "";
		try
		{
			sparkDirectory = new File(installerContext.getInstallationDirectory(), "Spark.exe");
			sparkPath = sparkDirectory.getCanonicalPath();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		if (sparkPath != null && sparkPath.length() > 0)
		{
			addSparkToStartup(sparkPath);
			
			setURI(sparkPath);
		}
		
		return true;
	}
	
	public void rollback(InstallContext installerContext)
	{
		WinRegistry.deleteValue(RegistryRoot.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", "Spark");
	}
	
	public void addSparkToStartup(String sparkPath)
	{
		try
		{
			WindowRegistry.setValue(RegistryRoot.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", "Spark", sparkPath);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	private void setURI(String path)
	{
		boolean exists = WinRegistry.keyExists(RegistryRoot.HKEY_CLASSES_ROOT, "xmpp");
		if (exists)
		{
		}
		WinRegistry.deleteKey(RegistryRoot.HKEY_CLASSES_ROOT, "xmpp", true);
		
		WinRegistry.createKey(RegistryRoot.KKEY_CLASSES_ROOT, "xmpp");
		WinRegistry.setValue(RegistryRoot.HKEY_CLASSES_ROOT, "xmpp", "", "URL:XMPP Address");
		WinRegistry.setValue(RegistryRoot.HKEY_CLASSES_ROOT, "xmpp", "URL_Protocol", "");
		
		WinRegistry.createKey(RegistryRoot.HKEY_CLASSES_ROOT, "xmpp\\shell\\open\\command");
		WinRegistry.setValue(RegistryRoot.HKEY_CLASSES_ROOT, "xmpp\\shell\\open\\command", "", path + " %1");
	}
}
